/**
 * Grid Service
 */
package cn.antia.cwin.grid;

import java.util.*;

import cn.antia.cep.common.*;
import cn.antia.cep.common.pool.AntiaPoolHelper;
import cn.antia.cwin.db.DbService;
import cn.antia.cwin.db.CwinSQLGene;
import cn.antia.cwin.ConfigException;
import cn.antia.db.JdbcSql;
import cn.antia.cwin.Output;
import cn.antia.cwin.NTableConvertor;
import cn.antia.cwin.Cele;

/**
 * @author sunkeei
 * @date Nov 21, 2007
 * @version 0.1
 * @time 
 */
public class GridService {
	private AntiaPoolHelper antiaPoolHelper;
	private DbService dbService;
    private CwinSQLGene cwinSQLGene;

    public AntiaPoolHelper getAntiaPoolHelper() {
		return antiaPoolHelper;
	}
	public void setAntiaPoolHelper(AntiaPoolHelper antiaPoolHelper) {
		this.antiaPoolHelper = antiaPoolHelper;
	}
	public DbService getDbService() {
		return dbService;
	}
	public void setDbService(DbService dbService) {
		this.dbService = dbService;
	}
    public CwinSQLGene getCwinSQLGene() {
        return cwinSQLGene;
    }

    public void setCwinSQLGene(CwinSQLGene cwinSQLGene) {
        this.cwinSQLGene = cwinSQLGene;
    }

    /**
	 * 取得单表表格数据
	 * @param id	gridId
	 * @return AntiaNormalTable(装满数据的)
	 */
	public AntiaNormalTable getSingleAntiaNormalTable(String id){
		return getSingleAntiaNormalTable(id,1);
	}
	/**
	 * 取得单表表格数据 
	 * @param id		gridId
	 * @param page		页数
	 * @return
	 */
	public AntiaNormalTable getSingleAntiaNormalTable(String id,int page){
		AntiaNormalTable table = new AntiaNormalTable();
		SingleGrid grid = antiaPoolHelper.getSingleGrid(id);
		String sql = grid.getSql();
		List<Map<Cele,Object>> result;		//查询结果
		int pagesize = grid.getPageSize();
		if(sql == null || sql.length() < 1){
			//记录总数
			String recordCountSql = getRecordCountSql(grid.getTable(), grid.getLimit());
			Integer count = dbService.queryFirstObject(recordCountSql);
			table.setRecordCount(count);
			//查询具体数据
			sql = getSingleSql(grid.getTable(),grid.getFields(),grid.getLimit());
			result = dbService.find(sql,"ID",true, page, pagesize);
		}else{
            Integer count = dbService.getRecordCount(sql);
			table.setRecordCount(count);
            result = dbService.find(sql,"ID",true,page,pagesize);
		}
		table.setRows(NTableConvertor.getDataList(grid.getFields(),grid.getExpanded(),result));
		table.setGridId(id);
		table.setId("tg_" + id);
		//表头
		table.setTh(NTableConvertor.getTableTH(grid.getFields(),grid.getExpanded(),table.getId()));
		//表描述
		table.setDesc(grid.getDesc());
		//取得查询条件
		table.setConditions(grid.getConditions());
		//分页信息
		table.setPageSize(grid.getPageSize());
		table.setCurrentPage(page);
		int rc = table.getRecordCount();
		table.setPageCount(rc % pagesize == 0 ? rc/pagesize : rc/pagesize + 1);
		return table;
	}
	
	/***
	 * 取得单表表格数据
	 * @param id grid id
	 * @param limits	conditions
	 * @return
	 */
	public AntiaNormalTable getSingleAntiaNormalTable(String id,Map<Cele,Object> limits){
		return getSingleAntiaNormalTable(id,limits,1);
	}
	/**
	 * 取得单表表格数据
	 * @param id		grid id
	 * @param limits	limits
	 * @param page		页数
	 * @return	
	 */
	public AntiaNormalTable getSingleAntiaNormalTable(String id,Map<Cele,Object> limits,int page){
		if(limits == null || limits.size() < 1){
			return getSingleAntiaNormalTable(id,page);
		}
		SingleGrid grid = antiaPoolHelper.getSingleGrid(id);
		int start = (page - 1) * grid.getPageSize();		//开始记录
		int end = start + grid.getPageSize();				//结束记录
		//设置条件的类型
		List<Cele> conds = grid.getConditions();
        for (Map.Entry<Cele, Object> entry : limits.entrySet()) {
            Cele ec = entry.getKey();
            for (Cele ec2 : conds) {
                if (ec.getField().getFieldName().equals(ec2.getField().getFieldName())) {
                    ec.getField().setDbType(ec2.getField().getDbType());
                    break;
                }
            }
        }
        
        //取出条件语句
		JdbcSql jdbcsql = cwinSQLGene.getConditionSql(limits);
		String subwhere = jdbcsql.getSql().substring(7);
		String where,sql;
		//查看是否有SQL语句
		if(grid.getSql() != null){
			String sql1 = grid.getSql();
			if(sql1.indexOf(" where ") > 0){
				String[] ss = sql1.split(" where ");
				if(ss.length != 2){
					AntiaLog.error("Grid config error:Cann't set limit contains string ' where ' GRID ID:" + id);
					throw new ConfigException("011","Grid id:" + id);
				}
				where = new StringBuffer(" where (").append(ss[1]).append(") and ").append(subwhere).toString();
				sql = ss[0] + where;
			}else{
				where = new StringBuffer(" where" ).append(subwhere).toString();
				sql = sql1 + where;
			}
		}else{
			//查询是否有限制语句，如果有，则加上
			if(grid.getLimit() != null){
				where = new StringBuffer(" where (").append(grid.getLimit()).append(")").append(" and ").append(subwhere).toString();
			}else{
				where = new StringBuffer(" where ").append(subwhere).toString();
			}
			sql = getSingleSql(grid.getTable(), grid.getFields(),"");
			sql = sql + where;
		}
		List<Map<Cele,Object>> list;
		list = dbService.find(jdbcsql);
        
        AntiaNormalTable table = new AntiaNormalTable();
		table.setRecordCount(list.size());
		table.setPageSize(grid.getPageSize());
		table.setCurrentPage(page);
		table.setPageCount(table.getRecordCount() % table.getPageSize() == 0 ? table.getRecordCount()/table.getPageSize() : table.getRecordCount()/table.getPageSize() + 1);
		if(start < list.size()){
			end = end < list.size() ? end : list.size();
			list = list.subList(start, end);
		}else{
			list = new ArrayList<Map<Cele,Object>>();
		}
		//设置数据行
		table.setRows(NTableConvertor.getDataList(grid.getFields(),grid.getExpanded(),list));
		table.setGridId(id);
		table.setId("tg_" + id);
		//表头
		table.setTh(NTableConvertor.getTableTH(grid.getFields(),grid.getExpanded(),table.getId()));
		//表描述
		table.setDesc(grid.getDesc());
		//取得查询条件
		table.setConditions(grid.getConditions());
		return table;
	}
	
	/**
	 * 取得单表查询的SQL
	 * @param table
	 * @param fields (GridField 列表)
	 * @param limit
	 * @return
	 */
	private String getSingleSql(String table, List<Output> fields,String limit){
		StringBuffer sb = new StringBuffer("select ");
		Output field;
		for(int i = 0;i<fields.size();i++){
			field = fields.get(i);
			if(i > 0){
				sb.append(",");
			}
			sb.append(field.getField());
		}
		sb.append(" from ").append(table);
		if(limit != null && limit.trim().length() > 0){
			sb.append(" where ").append(limit);
		}
		return sb.toString();
	}
	private String getRecordCountSql(String table, String limit){
		StringBuffer sb;
		if(limit != null && limit.trim().length() > 0){
			sb = new StringBuffer("select count(*) c1 from ").append(table).append(" where ").append(limit);
		}else{
			sb = new StringBuffer("select count(*) c1 from ").append(table);
		}
		return sb.toString();
	}
	
}